package me.duzhi.blog.controller;

import io.jpress.Consts;
import io.jpress.core.JBaseController;
import io.jpress.message.Actions;
import io.jpress.message.MessageKit;
import io.jpress.model.User;
import io.jpress.model.query.UserQuery;
import io.jpress.router.RouterMapping;
import io.jpress.utils.CookieUtils;
import io.jpress.utils.EncryptUtils;
import io.jpress.utils.StringUtils;

import java.util.Date;

/**
 * 用户中心
 *
 * @author ashang.peng@aliyun.com
 * @date 十二月 21, 2016
 */
@RouterMapping(url = "/member", viewPath = "/templates/duzhi/")
public class _UserController extends JBaseController {
    public void login() {
        String returnUrl = getPara("RT");
        //回叙跳转用的
        if (StringUtils.isNotBlank(returnUrl)) {
            CookieUtils.put(this, "returnUrl", returnUrl);
        }
        String action = getPara("action");
        if (action == null & !"POST".equals(this.getRequest().getMethod())) {
            render("_user_login.html");
            return;
        }
        switch (action) {
            case "ajaxregister":
                doRegister();
                break;
            case "ajaxlogin":
                doLogin();
                break;
           /* case "loginout":
                loginout();
                break;*/
            default:
                render("_user_login.html");
        }
    }

    public void loginout() {
        CookieUtils.remove(this, Consts.COOKIE_LOGINED_USER);
        redirect("/?loginout");
    }

    public void later(){
       String returnUrl= CookieUtils.get(this,"returnUrl");
       CookieUtils.remove(this,"returnUrl");
       setAttr("returnUrl",returnUrl);
        render("_user_later.html");
    }

    private void doLogin() {
        String username = getPara("username");
        String password = getPara("password");
        if (!StringUtils.areNotEmpty(username, password)) {
            render("_user_login.html");
            return;
        }

        User user = UserQuery.me().findUserByUsername(username);
        if (EncryptUtils.verlifyUser(user.getPassword(), user.getSalt(), password) && !user.isAdministrator()) {
            MessageKit.sendMessage(Actions.USER_LOGINED, user);
            CookieUtils.put(this, Consts.COOKIE_LOGINED_USER, user.getId().toString());
            renderAjaxResultForSuccess("登录成功");
        } else {
            renderAjaxResultForError("密码错误");
        }
    }

    private void doRegister() {
        if(!validateCaptcha("tin_captcha")){
            renderAjaxResultForError("验证码不正确");
            return;
        }
        String username = getPara("username");
        String email = getPara("email");
        String password = getPara("password");
        User dbUser = UserQuery.me().findUserByUsername(username);
        if (dbUser != null) {
            renderAjaxResultForError("该用户名已经存在，不能注册。");
            return;
        }
        if (StringUtils.isNotBlank(email)) {
            dbUser = UserQuery.me().findUserByEmail(email);
            if (dbUser != null) {
                renderAjaxResultForError("邮件地址已经存在，不能添加该邮箱。");
                return;
            }
        }
        // 用户修改了密码
        // 新增用户
        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        String salt = EncryptUtils.salt();
        user.setSalt(salt);
        user.setCreated(new Date());
        if (StringUtils.isNotEmpty(password)) {
            password = EncryptUtils.encryptPassword(password, salt);
            user.setPassword(password);
        }
        user.saveOrUpdate();
        CookieUtils.put(this,Consts.COOKIE_LOGINED_USER,user.getId().toString());
        renderAjaxResultForSuccess("ok");
    }


}
